package com.supor.aiot.common.ui.view;

import android.Manifest;
import android.content.ContentUris;
import android.text.TextUtils;

import com.alibaba.fastjson.JSONObject;
import com.alipay.mobile.h5container.api.H5BridgeContext;
import com.alipay.mobile.h5container.api.H5Event;
import com.alipay.mobile.h5container.api.H5EventFilter;
import com.alipay.mobile.h5container.api.H5SimplePlugin;
import com.android.baseconfig.base.BaseSharedPreferences;
import com.android.baseconfig.common.rxpermissions2.RxPermissions;
import com.android.baseconfig.common.utils.Logc;
import com.android.baseconfig.common.utils.SystemUtils;
import com.android.baseconfig.common.utils.ThreadUtils;
import com.android.baseconfig.common.utils.ToastUtils;
import com.supor.aiot.common.app.AppAgent;
import com.supor.aiot.common.app.Constants;
import com.supor.aiot.common.app.SuporPresenter;
import com.supor.aiot.common.helper.GlobalDataCache;
import com.supor.aiot.common.helper.WsHelper;
import com.supor.aiot.common.utils.CalendarReminderUtils;
import com.supor.aiot.common.utils.MarketUtils;
import com.supor.aiot.common.utils.NotNullUtils;
import com.supor.nfc.lib.utils.NfcUtils;

import static com.alipay.mobile.h5container.api.H5Plugin.CommonEvents.EXIT_SESSION;
import static com.alipay.mobile.h5container.api.H5Plugin.CommonEvents.H5_PAGE_PHYSICAL_BACK;

import androidx.fragment.app.FragmentActivity;

import java.text.SimpleDateFormat;

public class SuporJSApiPlugin extends H5SimplePlugin {

    public static String TINY_ACTION = null;

    @Override
    public void onPrepare(H5EventFilter filter) {
        super.onPrepare(filter);
        // onPrepare 中需要 add 进来
        filter.addAction(Constants.Fun.sendOnline);
        filter.addAction(Constants.Fun.sendCmd);
        filter.addAction(Constants.Fun.sendShareMsg);
        filter.addAction(Constants.Fun.sendShowNavigationBar);
        filter.addAction(Constants.Fun.sendUserInfo);
        filter.addAction(Constants.Fun.sendCmccAuthLogin);
        filter.addAction(Constants.Fun.sendGetAppInfo);
        filter.addAction(Constants.Fun.sendSetAppInfo);
        filter.addAction(Constants.Fun.sendSwitchServer);
        filter.addAction(Constants.Fun.sendSaveInfo);
        filter.addAction(Constants.Fun.sendJumpMemberCenter);
        filter.addAction(Constants.Fun.sendConfigNetwork);
        filter.addAction(Constants.Fun.sendUrlDisplay);
        filter.addAction(Constants.Fun.sendRequestPermission);
        filter.addAction(Constants.Fun.sendFeedback);
        filter.addAction(Constants.Fun.sendSaveUpgradeInfo);
        filter.addAction(Constants.Fun.sendGetUpgradeInfo);
        filter.addAction(Constants.Fun.sendStartPage);
        filter.addAction(Constants.Fun.sendStateChange);
        filter.addAction(Constants.Fun.sendTikRecipeStateChange);
        filter.addAction(Constants.Fun.sendTikRecipePageStart);
        filter.addAction(Constants.Fun.showToast);
        filter.addAction(Constants.Fun.addToCalendar);
        filter.addAction(Constants.Fun.removeFromCalendar);
        filter.addAction(Constants.Fun.sendNFCBlender);
        // 主界面返回action
        filter.addAction(EXIT_SESSION);
        // 小程序退出按钮
        filter.addAction(H5_PAGE_PHYSICAL_BACK);
        filter.addAction(CommonEvents.H5_AL_JSAPI_RESULT_ERROR);
    }

    /**
     * 小程序端发送消息到原生端
     *
     * @param event   h5 event
     * @param context bridge context，上下文，不做持有操作
     * @return true消耗事件|false不消耗事件
     */
    @Override
    public boolean handleEvent(H5Event event, H5BridgeContext context) {
        String action = event.getAction();
        // Logc.d("H5 action: " + action);
        JSONObject params = event.getParam();
        // Logc.i("H5 params: " + (params != null ? params.toJSONString() : "null"));
        if (Constants.Fun.sendOnline.equalsIgnoreCase(action)) {
            if (isFastClick(sendOnlineTime)) {
                return false;
            }
            sendOnlineTime = System.currentTimeMillis();
            String mac = params.getString(Constants.Key.param_mac);

            JSONObject result = new JSONObject();
            result.put(Constants.Key.param_success, 1);
            result.put(Constants.Key.param_online, WsHelper.getInstance().getOnOffStatus(mac));
            // 将结果返回给小程序
            context.sendBridgeResult(result);
        } else if (Constants.Fun.sendCmd.equalsIgnoreCase(action)) {
            if (isFastClick(sendCmdTime)) {
                return false;
            }
            sendCmdTime = System.currentTimeMillis();
            int cmd = params.getIntValue(Constants.Key.param_cmd);
            String mac = params.getString(Constants.Key.param_mac);
            String did = params.getString(Constants.Key.param_did);
            String value = params.getString(Constants.Key.param_value);
            SuporPresenter.getInstance().sendCmd(cmd, mac, did, value);

            JSONObject result = new JSONObject();
            result.put(Constants.Key.param_success, 1);
            context.sendBridgeResult(result);
        } else if (Constants.Fun.sendDeviceTree.equalsIgnoreCase(action)) {
            if (isFastClick(sendDeviceTreeTime)) {
                return false;
            }

            JSONObject result = new JSONObject();
            result.put(Constants.Key.param_device, GlobalDataCache.deviceTree);
            result.put(Constants.Key.param_success, 1);
            context.sendBridgeResult(result);
        } else if (Constants.Fun.sendShowNavigationBar.equalsIgnoreCase(action)) {
            if (isFastClick(sendShowNavigationBarTime)) {
                return false;
            }
            sendShowNavigationBarTime = System.currentTimeMillis();
            int visibility = params.getIntValue(Constants.Key.param_visibility);
            SuporPresenter.getInstance().sendShowNavigationBar(visibility);

            JSONObject result = new JSONObject();
            result.put(Constants.Key.param_success, 1);
            context.sendBridgeResult(result);
        } else if (Constants.Fun.sendShareMsg.equalsIgnoreCase(action)) {
            if (isFastClick(sendShareMsgTime)) {
                return false;
            }
            Logc.i("sendShareMsg jo: " + params);
            sendShareMsgTime = System.currentTimeMillis();
            SuporPresenter.getInstance().sendShareMsg(params);

            JSONObject result = new JSONObject();
            result.put(Constants.Key.param_success, 1);
            context.sendBridgeResult(result);
        } else if (Constants.Fun.sendUserInfo.equalsIgnoreCase(action)) {
            if (isFastClick(sendUserInfoTime)) {
                return false;
            }
            sendUserInfoTime = System.currentTimeMillis();
            SuporPresenter.getInstance().sendUserInfo(params);

            JSONObject result = new JSONObject();
            result.put(Constants.Key.param_success, 1);
            context.sendBridgeResult(result);
        } else if (Constants.Fun.sendCmccAuthLogin.equalsIgnoreCase(action)) {
            if (isFastClick(sendCmccAuthLoginTime)) {
                return false;
            }
            sendCmccAuthLoginTime = System.currentTimeMillis();
            int state = params.getIntValue(Constants.Key.param_state);
            SuporPresenter.getInstance().sendCmccAuthLogin(state);

            JSONObject result = new JSONObject();
            result.put(Constants.Key.param_success, 1);
            context.sendBridgeResult(result);
        } else if (Constants.Fun.sendGetAppInfo.equalsIgnoreCase(action)) {
            SuporPresenter.getInstance().sendGetAppInfo(params);
            JSONObject result = new JSONObject();
            result.put(Constants.Key.param_success, 1);
            result.put(Constants.Key.param_appVersion, SystemUtils.getVerName(AppAgent.getApp()));
            result.put(Constants.Key.param_server, AppAgent.currentServer);
            // String saveInfo = BaseSharedPreferences.getString(AppAgent.getApp(),
            //         Constants.Key.param_saveInfo);
            // result.put(Constants.Key.param_getInfo, saveInfo);
            String tinyVersion = BaseSharedPreferences.getString(AppAgent.getApp(),
                    Constants.Key.param_tinyVersion);
            if (!TextUtils.isEmpty(tinyVersion)) {
                result.put(Constants.Key.param_tinyVersion, tinyVersion);
            }
            // int firstOpenApp = BaseSharedPreferences.getInt(AppAgent.getApp(),
            //         Constants.Key.param_firstOpenApp, 1);
            // result.put(Constants.Key.param_firstOpenApp, firstOpenApp);
            // int authPrivacyPolicy = BaseSharedPreferences.getInt(AppAgent.getApp(),
            //         Constants.Key.param_authPrivacyPolicy);
            // result.put(Constants.Key.param_authPrivacyPolicy, authPrivacyPolicy);
            result.put(Constants.Key.param_supportNFC, (NfcUtils.NFC_STATE == 1 ? 0 : 1));
            result.put(Constants.Key.param_wxInstalled,
                    (MarketUtils.getTools().isInstalled(AppAgent.getApp(), Constants.App.WeixinPackage) ? 1 : 0));
            result.put(Constants.Key.param_dyInstalled,
                    (MarketUtils.getTools().isInstalled(AppAgent.getApp(), Constants.App.DouyinPackage) ? 1 : 0));
            result.put(Constants.Key.param_wbInstalled,
                    (MarketUtils.getTools().isInstalled(AppAgent.getApp(), Constants.App.WeiboPackage) ? 1 : 0));
            String user = BaseSharedPreferences.getString(AppAgent.getApp(), Constants.Key.USER_INFO);
            result.put(Constants.Key.param_userInfo, user);
            Logc.i("report sendGetAppInfo: " + result.toJSONString());
            context.sendBridgeResult(result);
            // Logc.e("sendGetAppInfo end");
        } else if (Constants.Fun.sendSetAppInfo.equalsIgnoreCase(action)) {
            if (isFastClick(sendSetAppInfoTime)) {
                return false;
            }
            sendSetAppInfoTime = System.currentTimeMillis();
            SuporPresenter.getInstance().sendSetAppInfo(params);

            JSONObject result = new JSONObject();
            result.put(Constants.Key.param_success, 1);
            context.sendBridgeResult(result);
        } else if (Constants.Fun.sendSaveInfo.equalsIgnoreCase(action)) {
            if (isFastClick(sendSaveInfoTime, 100)) {
                Logc.i("sendSaveInfo fast");
                return false;
            }
            sendSaveInfoTime = System.currentTimeMillis();

            // 0获取保存信息（小程序获取原生保存的信息）
            // 1存储信息（小程序保存信息至原生）
            int type = params.getIntValue(Constants.Key.param_type);
            JSONObject result = new JSONObject();
            result.put(Constants.Key.param_success, 1);
            String key = params.getString(Constants.Key.param_key);
            if (TextUtils.isEmpty(key)) {
                context.sendBridgeResult(result);
                return false;
            }
            if (type == 0) {
                String saveInfo = BaseSharedPreferences.getString(AppAgent.getApp(),
                        key);
                result.put(Constants.Key.param_value, saveInfo);
                Logc.i("sendSaveInfo retrun jo: " + saveInfo);
            } else if (type == 1) {
                String value = params.getString(Constants.Key.param_value);
                BaseSharedPreferences.setString(AppAgent.getApp(),
                        key, value);
            }
            context.sendBridgeResult(result);

        } else if (Constants.Fun.sendSwitchServer.equalsIgnoreCase(action)) {
            if (isFastClick(sendSwitchServerTime)) {
                return false;
            }
            sendSwitchServerTime = System.currentTimeMillis();
            SuporPresenter.getInstance().sendSwitchServer(params.getIntValue(Constants.Key.param_server));

            JSONObject result = new JSONObject();
            result.put(Constants.Key.param_success, 1);
            context.sendBridgeResult(result);
        } else if (Constants.Fun.sendJumpMemberCenter.equalsIgnoreCase(action)) {
            if (isFastClick(sendJumpMemberCenterTime)) {
                return false;
            }
            sendJumpMemberCenterTime = System.currentTimeMillis();
            int type = params.getIntValue(Constants.Key.param_type);
            SuporPresenter.getInstance().getShareHelper().startWXTiny(type);

            JSONObject result = new JSONObject();
            result.put(Constants.Key.param_success, 1);
            context.sendBridgeResult(result);
        } else if (Constants.Fun.sendConfigNetwork.equalsIgnoreCase(action)) {
            if (isFastClick(sendConfigNetworkTime)) {
                return false;
            }
            sendConfigNetworkTime = System.currentTimeMillis();
            SuporPresenter.getInstance().sendConfigNetwork(params);

            JSONObject result = new JSONObject();
            result.put(Constants.Key.param_success, 1);
            context.sendBridgeResult(result);
        } else if (Constants.Fun.sendUrlDisplay.equalsIgnoreCase(action)) {
            if (isFastClick(sendUrlDisplayTime)) {
                return false;
            }
            sendUrlDisplayTime = System.currentTimeMillis();
            SuporPresenter.getInstance().sendUrlDisplay(params);

            JSONObject result = new JSONObject();
            result.put(Constants.Key.param_success, 1);
            context.sendBridgeResult(result);
        } else if (Constants.Fun.sendRequestPermission.equalsIgnoreCase(action)) {
            if (isFastClick(sendRequestPermissionTime)) {
                return false;
            }
            sendRequestPermissionTime = System.currentTimeMillis();
            SuporPresenter.getInstance().sendRequestPermission(params);

            JSONObject result = new JSONObject();
            result.put(Constants.Key.param_success, 1);
            context.sendBridgeResult(result);
        } else if (Constants.Fun.sendFeedback.equalsIgnoreCase(action)) {
            if (isFastClick(sendFeedbackTime)) {
                return false;
            }
            sendFeedbackTime = System.currentTimeMillis();
            SuporPresenter.getInstance().sendFeedback();

            JSONObject result = new JSONObject();
            result.put(Constants.Key.param_success, 1);
            context.sendBridgeResult(result);
        } else if (Constants.Fun.sendSaveUpgradeInfo.equalsIgnoreCase(action)) {
            int state = params.getIntValue(Constants.Key.param_state);
            String paramStr = params.getString(Constants.Key.param_params);
            SuporPresenter.getInstance().sendSaveUpgradeInfo(state, paramStr);

            JSONObject result = new JSONObject();
            result.put(Constants.Key.param_success, 1);
            context.sendBridgeResult(result);
        } else if (Constants.Fun.sendGetUpgradeInfo.equalsIgnoreCase(action)) {
            if (isFastClick(sendGetUpgradeInfoTime)) {
                return false;
            }
            sendGetUpgradeInfoTime = System.currentTimeMillis();
            String upgradeInfo = BaseSharedPreferences.getString(AppAgent.getApp(),
                    Constants.Key.param_upgradeInfo);

            JSONObject result = new JSONObject();
            result.put(Constants.Key.param_params, upgradeInfo);
            result.put(Constants.Key.param_success, 1);
            context.sendBridgeResult(result);
        } else if (Constants.Fun.sendStartPage.equalsIgnoreCase(action)) {
            if (isFastClick(sendStartPageTime)) {
                return false;
            }
            sendStartPageTime = System.currentTimeMillis();
            SuporPresenter.getInstance().sendStartPage(params);

            JSONObject result = new JSONObject();
            result.put(Constants.Key.param_success, 1);
            context.sendBridgeResult(result);
        } else if (Constants.Fun.sendStateChange.equalsIgnoreCase(action)) {
            if (isFastClick(sendStateChangeTime)) {
                return false;
            }
            sendStateChangeTime = System.currentTimeMillis();
            SuporPresenter.getInstance().sendStateChange(params);

            JSONObject result = new JSONObject();
            result.put(Constants.Key.param_success, 1);
            context.sendBridgeResult(result);
        } else if (Constants.Fun.sendTikRecipeStateChange.equalsIgnoreCase(action)) {
            if (isFastClick(sendTikRecipeStateChangeTime)) {
                return false;
            }
            sendTikRecipeStateChangeTime = System.currentTimeMillis();
            SuporPresenter.getInstance().sendTikRecipeStateChange(params);

            JSONObject result = new JSONObject();
            result.put(Constants.Key.param_success, 1);
            context.sendBridgeResult(result);
        } else if (Constants.Fun.addToCalendar.equalsIgnoreCase(action)) {
            if (isFastClick(sendAddtoCalendarTime)) {
                return false;
            }
            sendAddtoCalendarTime = System.currentTimeMillis();
            System.out.println("Constants.Fun.addToCalendar thread " + Thread.currentThread().getName());
            new RxPermissions((FragmentActivity) AppAgent.getCurrentActivity()).request(
                    Manifest.permission.READ_CALENDAR,
                    Manifest.permission.WRITE_CALENDAR)
                    .subscribe(aBoolean -> {
                        if (aBoolean) {
                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");

                            long tpid = CalendarReminderUtils.addCalendarEvent(AppAgent.getCurrentActivity(),
                                    NotNullUtils.getNotNullValue(params.getString("title")),
                                    NotNullUtils.getNotNullValue(params.getString("title")),
                                    format.parse(NotNullUtils.getNotNullValue(params.getString("startTime"))),
                                    format.parse(NotNullUtils.getNotNullValue(params.getString("endTime"))),
                                    0);
                            JSONObject result = new JSONObject();
                            result.put(Constants.Key.param_success, 1);
                            result.put(Constants.Key.param_resultid, String.valueOf(tpid));
                            context.sendBridgeResult(result);
//                            ToastUtils.getInstance().showToast(AppAgent.getCurrentActivity(), "添加到系统日历成功");
                        } else {
                            Logc.i("permission request: failed");
                        }
                    });


//            long tpid = SuporPresenter.getInstance().addToCalendar(params);
//            JSONObject result = new JSONObject();
//            result.put(Constants.Key.param_success, 1);
//            result.put(Constants.Key.param_resultid, String.valueOf(tpid));
//            context.sendBridgeResult(result);
        } else if (Constants.Fun.removeFromCalendar.equalsIgnoreCase(action)) {
            if (isFastClick(sendRemovetoCalendarTime)) {
                return false;
            }
            sendRemovetoCalendarTime = System.currentTimeMillis();
            new RxPermissions((FragmentActivity) AppAgent.getCurrentActivity()).request(Manifest.permission.READ_CALENDAR,
                    Manifest.permission.WRITE_CALENDAR)
                    .subscribe(aBoolean -> {
                        if (aBoolean) {
                            CalendarReminderUtils.deleteCalendarEvent(AppAgent.getCurrentActivity(),
                                    params.getString("id"));
//                                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");

//                                CalendarReminderUtils.addCalendarEvent(getActivity(),
//                                        "事件标题",
//                                        "事件描述description",
//                                        format.parse("2022-01-19 17:00"),
//                                        0);
                            JSONObject result = new JSONObject();
                            result.put(Constants.Key.param_success, 1);
                            context.sendBridgeResult(result);
//                            ToastUtils.getInstance().showToast(AppAgent.getCurrentActivity(), "删除到系统日历成功");
                        } else {
                            Logc.i("permission request: failed");
                        }
                    });
        } else if (Constants.Fun.showToast.equalsIgnoreCase(action)) {
            SuporPresenter.getInstance().showToast(params);

            JSONObject result = new JSONObject();
            result.put(Constants.Key.param_success, 1);
            context.sendBridgeResult(result);
        } else if (Constants.Fun.sendTikRecipePageStart.equalsIgnoreCase(action)) {
            if (isFastClick(sendTikRecipePageStartTime)) {
                return false;
            }
            sendTikRecipePageStartTime = System.currentTimeMillis();
            SuporPresenter.getInstance().sendTikRecipePageStart(params);

            JSONObject result = new JSONObject();
            result.put(Constants.Key.param_success, 1);
            context.sendBridgeResult(result);
        } else if (Constants.Fun.sendNFCBlender.equalsIgnoreCase(action)) {
            if (isFastClick(sendNFCBlenderTime, 500)) {
                return false;
            }
            sendNFCBlenderTime = System.currentTimeMillis();
            SuporPresenter.getInstance().sendNFCBlender(params);

            JSONObject result = new JSONObject();
            result.put(Constants.Key.param_success, 1);
            context.sendBridgeResult(result);
        } else if (H5_PAGE_PHYSICAL_BACK.equalsIgnoreCase(action) || EXIT_SESSION.equalsIgnoreCase(action)) {
            TINY_ACTION = action;
            ThreadUtils.execute(() -> TINY_ACTION = null, 1000);
            return false;
        } else if (CommonEvents.H5_AL_JSAPI_RESULT_ERROR.equalsIgnoreCase(action)) {
            Logc.e("H5_AL_JSAPI_RESULT_ERROR: ------");
            return true;
        }

        return false;
    }

    private static long sendOnlineTime;
    private static long sendCmdTime;
    private static long sendDeviceTreeTime;
    private static long sendShowNavigationBarTime;
    private static long sendShareMsgTime;
    private static long sendUserInfoTime;
    private static long sendCmccAuthLoginTime;
    private static long sendSetAppInfoTime;
    private static long sendSaveInfoTime;
    private static long sendSwitchServerTime;
    private static long sendJumpMemberCenterTime;
    private static long sendConfigNetworkTime;
    private static long sendUrlDisplayTime;
    private static long sendRequestPermissionTime;
    private static long sendFeedbackTime;
    private static long sendLoadingTime;
    private static long sendGetUpgradeInfoTime;
    private static long sendStartPageTime;
    private static long sendStateChangeTime;
    private static long sendTikRecipeStateChangeTime;
    private static long sendTikRecipePageStartTime;
    private static long sendNFCBlenderTime;
    private static long sendAddtoCalendarTime;
    private static long sendRemovetoCalendarTime;
    private static long sendShowToastTime;

    /**
     * mPaaS框架有bug，偶尔jsapi接口会连续接收两次，此处做防抖处理
     */
    public synchronized static boolean isFastClick(long funLastClick) {
        return (System.currentTimeMillis() - funLastClick) < 150;
    }

    /**
     * mPaaS框架有bug，偶尔jsapi接口会连续接收两次，此处做防抖处理
     */
    public synchronized static boolean isFastClick(long funLastClick, int time) {
        return (System.currentTimeMillis() - funLastClick) < time;
    }
}
